package com.kly.job;

import com.kly.constant.UserConstant;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author admin
 * @date 2025/2/22
 */
// @Component
@Slf4j
public class CacheUsers {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(cron = "0 0/1 * * * *")
    public void cacheUsers() {

        RLock lock = redissonClient.getLock(UserConstant.USER_LOCK_KEY);

        // 加锁
        try {
            if(lock.tryLock(0, -1, TimeUnit.SECONDS)) {
                log.info("缓存用户信息");
                stringRedisTemplate.opsForValue().set("user:cache:", "user", 30, TimeUnit.SECONDS);
            }
        } catch (InterruptedException e) {
            log.error("缓存用户信息失败");
        } finally {
            if(lock.isHeldByCurrentThread()) {
                log.info("释放锁");
                lock.unlock();
            }
        }


    }
}
